<template>
  <div class="export-container">
    <el-form :inline="true" :model="form">
      <el-form-item label="Wafer Lot">
        <el-input v-model="form.waferLot" placeholder="输入 Wafer Lot" />
      </el-form-item>
      <el-form-item label="Lot No">
        <el-input v-model="form.lotNo" placeholder="输入 Lot No" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="exportExcel">导出 Excel</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";

defineOptions({
  name: "cpDataTime"
});

const API_URL_EXPORT = "http://10.20.5.21:8080/api/export/excel";

const form = ref({
  waferLot: "",
  lotNo: ""
});

let loadingInstance = null;

const exportExcel = async () => {
  try {
    const params = {
      waferLot: form.value.waferLot,
      lotNo: form.value.lotNo
    };

    loadingInstance = ElLoading.service({
      lock: true,
      text: "正在导出excel，请稍候...",
      background: "rgba(0,0,0,0.3)"
    });

    const response = await axios.get(API_URL_EXPORT, {
      params,
      responseType: "blob" // 关键：接收的是文件流
    });

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });

    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = `CP_Data_${new Date().toISOString().slice(0, 19).replace(/[-T:]/g, "")}.xlsx`;
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    if (error.response && error.response.data instanceof Blob) {
      const blob = error.response.data;
      const reader = new FileReader();
      reader.onload = () => {
        try {
          // 尝试解析JSON错误信息
          const errorData = JSON.parse(reader.result);
          ElMessage.error(errorData.message || "未找到相关记录");
        } catch (e) {
          // 非JSON格式，直接读取文本或默认消息
          ElMessage.error(reader.result.toString() || "请求失败");
        }
      };
      reader.onerror = () => {
        ElMessage.error("解析错误信息失败");
      };
      reader.readAsText(blob);
    } else {
      // 其他错误（如网络问题）
      ElMessage.error(error.message || "请求失败");
    }
  } finally {
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};
</script>

<style scoped>
.export-container {
  padding: 20px;
}
</style>
